<template>
  <div>
    <mb-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      :list = "list"
      :listMeta = "listMeta"
      @load="onLoad"
      @item-click="onItemClick"
    />
    <div class="palette-button">
      <van-button 
        type="info"
        icon="edit" 
        round
        @click="editBtnHandle"
        v-if="toolbar.type == 'apply'"
      >{{toolbar.title}}</van-button>
    </div>
    <van-action-sheet 
      v-model="actionShow" 
      :actions="actions" 
      @select="onActionSelect" 
      cancel-text="取消"/>
  </div>
</template>
<script>
import { getMenuInfo, divideUrlAndQuery, serialize } from 'utils'
import { request } from 'utils/http'
import MbList from '../components/mb-list/index.vue'

export default {
  name: 'mb-form',
  components:{
    [MbList.name]: MbList
  },
  /**
   * @queryPath [String] 列表数据请求url
   * @params [Object] 列表数据请求参数 
   * @pageSize [Number] 列表数据请求参数之页显示数据数
   * @pageNumber [Number] 列表数据请求参数之页数
   * @loading [Boolean] van-list加载状态
   * @finished [Boolean] van-list是否完成状态
   * @error [Boolean] van-list是否报错状态
   * @item [Object] 单行数据
   * @list [Array] van-list数据
   * @listMeta [Array] van-list需要显示的字段名称
   * @querySetting [String] van-list数据请求参数
   * @toolbar [Object] 新增按钮信息
   * @actionShow [Boolean] actionsheet操作开关
   * @actions [Array] 操作
   */
  data () {
    return {
      queryPath: '',
      params: {},
      pageSize: 10,
      pageNumber: 1,
      loading: false,
      finished: false,
      error: false,
      item: {},
      list: [],
      listMeta: [],
      querySetting: null,
      toolbar: {},
      actionShow: false,
      actions: []
    }
  },
  props: ['searchVal'],
  beforeRouteUpdate (to, from, next) {
    // ...
    next()
    this.init()
  },
  mounted() {
    this.init();
  },
  watch: {
    searchVal: function(val) {
      this.querySetting = !val.length ? '' : JSON.stringify(val);
      this.pageNumber = 1;
      this.list = [];
      this.loading = false;
      this.finished = false;
      this.error = false;
      this.getList();
    }
  },
  methods: {
    onLoad() {
      if(this.queryPath && this.list.length) {
        this.pageNumber ++;
        this.getList();
      }
    },
    editBtnHandle() {
      const _this = this;
      try {
        let noticeurl = "/sys/" + window.appNameEn + "/public/help/notice.json" ;
        let beforeClose = function(action, done) {
          if (action === 'confirm') {
            _this.$router.push({ 
              name: 'form-add',
              path: '/form-add', 
              params: {
                toolbar: _this.toolbar
              }
            })
          }
          done();
        }
        request(noticeurl).then((res) => {
          if(res) {
            _this.$dialog.confirm({
              title: res.title || "须知",
              message: res.content,
              beforeClose
            });
          } else (
            _this.$router.push({ 
              name: 'form-add',
              path: '/form-add', 
              params: {
                toolbar: _this.toolbar
              }
            })
          )
        })
      } catch (err) {
        console.error(err);
        this.$router.push({ 
          name: 'form-add',
          path: '/form-add', 
          params: {
            toolbar: this.toolbar
          }
        })
      }
    },
    onItemClick(item) {
      this.item = item;
      // 规则参看 李忻钧《列表的权限及控制按钮处理.docx》
      this.actions = this.actions.map((action) => {
        action.disabled = false;
        action.manage = action.manage || 0;
        if(!this.judgeVerify(item, action) || (item['$$manage'] <= action.manage)){
          action.disabled = true;
        }
        return action
      })
      this.actionShow = true;
    },
    //权限判断
    judgeVerify(row, item){
      let verify = item.verify
      for (let key in verify) {
        let checkArr = verify[key];
        let tmpResult = false;
        for (let i = 0; i < checkArr.length; i++) {
          if (checkArr[i] === row[key]) {
            tmpResult = true;
            break;
          }
        }
        if (!tmpResult) {
          return false;
        }
      }
      return true;
    },
    onActionSelect(action) {
      if(action.id === "edit" || action.id === "modify") {
        const _this = this;
        try {
          let noticeurl = "/sys/" + window.appNameEn + "/public/help/notice.json" ;
          let beforeClose = function(id, done) {
            if (id === 'confirm') {
              _this.$router.push({ 
                name: 'form-operation',
                path: '/form-operation', 
                params: {
                  item: _this.item,
                  toolbar: action,
                }
              })
            }
            done();
          }
          request(noticeurl).then((res) => {
            if(res) {
              _this.$dialog.confirm({
                title: res.title || "须知",
                message: res.content,
                beforeClose
              });
            } else (
              _this.$router.push({ 
                name: 'form-operation',
                path: '/form-operation', 
                params: {
                  item: _this.item,
                  toolbar: action,
                }
              })
            )
          })
        }catch(err) {
          console.error(err);
          this.$router.push({ 
            name: 'form-operation',
            path: '/form-operation', 
            params: {
              item: this.item,
              toolbar: action,
            }
          })
        }
      }else{
        this.$router.push({ 
          name: 'form-operation',
          path: '/form-operation', 
          params: {
            item: this.item,
            toolbar: action,
          }
        })
      }
      this.actionShow = false;
    },

    init() {
      const _this = this;
      const menuName = this.$route.params.name;
      const menuInfo = getMenuInfo(menuName);
      this.list = [];
      this.loading = false;
      this.finished = false;
      this.error = false;
      this.pageNumber = 1;
      this.listMeta = [];
      this.toolbar = {};
      if (!menuInfo) return
      this.formUrl = menuInfo.url.replace('showGrid', 'showForm');
      let pro = new Promise( resolve => {
        request(menuInfo.url, {query: menuInfo.params}).then(res => {
          if(res.code !== "0" || !res.models) {
            this.$notify({ type: 'danger', message: '获取模型失败！' });
            return
          }

          const data = res.models;
          _this.$parent.dataModel = data;

          // 列表数据准备
          data.gridMeta.forEach(meta => {
            if(!/^___/.test(meta.name)) _this.listMeta.push(meta.name);
          });
          if(_this.listMeta.length > 3) _this.listMeta = _this.listMeta.slice(0,3);
          resolve(data);

        });
      });
      pro.then( data => {
        let queryPath = divideUrlAndQuery(data.queryPath);
        _this.queryPath = queryPath.url;
        _this.params = queryPath.params;
        _this.getList();
        let actionsUrl = "/sys/eetablecore/options.json";
        request( actionsUrl ).then( res => {
          // [操作] 类型合并
          let originOpt = Object.assign([], data.options);
          console.log(originOpt)
          originOpt = originOpt.map( opt => {
            return _this.mergeBtnInfo(res[opt.id], opt, res._keepNames);
          })
          _this.actions = originOpt.filter( option => {
            if(option.id === "modify" || option.id === "query" || option.id === "edit" || option.id === "check") {
              option.name = option.title;
              option.gridAlias = data.gridAlias;
              option.formUrl = _this.formUrl
            }
            return option.id === "modify" || option.id === "query" || option.id === "edit" || option.id === "check"
          })
          // 悬浮【发起】按钮数据合并整理 type = apply
          if( data.toolbar && data.toolbar.length ) {
            let toolbar = data.toolbar.filter( item => {
              return item.type === 'apply'
            });
            if(toolbar && toolbar.length) {
              toolbar = toolbar[0];
              _this.toolbar = _this.mergeBtnInfo(res[toolbar.id], toolbar, res._keepNames);
              _this.toolbar.gridAlias = data.gridAlias;
              _this.toolbar.formUrl = _this.formUrl;
            }
          }
        })
      })
    },
    getList() {
      const _this = this;
      request(_this.queryPath, {
        method: "POST",
        data: serialize({
          ...this.params,
          querySetting: this.querySetting || '', 
          pageSize: this.pageSize,
          pageNumber: this.pageNumber
        }),
        headers: {
          "content-type": "application/x-www-form-urlencoded"
        }
      }).then(res => {
          _this.loading = false;
          if(!res || res.code !== "0") {
            _this.error = true;
            _this.$notify({ type: 'danger', message: '获取数据失败' });
            return
          }
          if(res.datas && res.datas && res.datas.result && res.datas.result.rows) {
            // 为每项row添加time参数
            res.datas.result.rows = res.datas.result.rows.map(row => {
              row.time = res.datas.time
              return row
            });

            _this.list = _this.list.concat(res.datas.result.rows);
            if(_this.list.length === res.datas.result.totalCount ) _this.finished = true;
          }
        })
    },
    mergeBtnInfo(urlOpt, opt, keepNames) {
      let realOpt = Object.assign({}, urlOpt);
      for (let i = 0; i < keepNames.length; i++) {
        let key = keepNames[i]
        if (opt[key] != null) {
          realOpt[key] = opt[key];
        }
      }
      return realOpt
    },
  }
}
</script>
<style>
.palette-button {
  position: fixed;
  bottom: 30px;
  right: 20px;
  z-index: 998;
}
</style>